package com.idopartx.phonelightning.ui.adapter

import android.widget.ImageView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.idopartx.phonelightning.R
import com.idopartx.phonelightning.common.Constant
import com.idopartx.phonelightning.entity.CallLightningCache
import com.idopartx.phonelightning.entity.CallLightningEntity
import com.tencent.mmkv.MMKV

class CallLightningAdapter(
    var onItemClick: (CallLightningEntity) -> Unit,
    var onEditClick: (CallLightningEntity, Int) -> Unit,
    var onDelClick: (CallLightningEntity, Int) -> Unit,
) :
    BaseQuickAdapter<CallLightningEntity, BaseViewHolder>(R.layout.adapter_call_lightning) {

    private var editStatus: Boolean = false

    fun setEditStatus(editStatus: Boolean?) {
        this.editStatus = editStatus == true
        notifyDataSetChanged()
    }

    override fun convert(
        holder: BaseViewHolder,
        item: CallLightningEntity
    ) {


        if (item.isCheck) {
            holder.itemView.setBackgroundResource(R.mipmap.icon_select_bg)
        } else {
            holder.itemView.setBackgroundResource(0)
        }

        holder.setGone(R.id.iv_icon_morse, item.isMorse != true)

        holder.getView<ImageView>(R.id.btn_edit).setOnClickListener {
            onEditClick(item, holder.adapterPosition - headerLayoutCount)
        }

        holder.getView<ImageView>(R.id.btn_del).setOnClickListener {
            onDelClick(item, holder.adapterPosition - headerLayoutCount)
        }

        if (editStatus) {
            holder.setGone(R.id.ll_edit, false)
            holder.itemView.setOnClickListener(null)
        } else {
            holder.setGone(R.id.ll_edit, true)
            holder.itemView.setOnClickListener {

                data.forEach {
                    it.isCheck = false
                }
                item.isCheck = true

                onItemClick(item)
                notifyDataSetChanged()
            }
        }

        holder.setText(R.id.tv_item, item.title)
    }


    fun resetCheckStatus() {
        data.forEach {
            it.isCheck = false
        }
        MMKV.defaultMMKV()
            .encode(
                Constant.MMKV_SAVE_CALL_LIGHTNING,
                CallLightningCache(data as ArrayList<CallLightningEntity>)
            )
        notifyDataSetChanged()
    }

}